package com.sinoparasoft.openstack4jdemo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.openstack4j.api.OSClient;
import org.openstack4j.model.telemetry.Sample;
import org.openstack4j.model.telemetry.SampleCriteria;
import org.openstack4j.openstack.OSFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("vm")
public class VMController {

	@RequestMapping(value="/", method=RequestMethod.GET)
	public String vm() {
		return "vm";
	}
	
	@RequestMapping(value="/cpu/{id}", method=RequestMethod.GET)
	@ResponseBody
	public Object cpuChart(@PathVariable("id") String id) {
		OSClient os = OSFactory.builder()
				.endpoint("http://192.168.211.11:5000/v2.0/")
				.credentials("admin", "76b41809b79b4310").tenantName("admin")
				.authenticate();	

		SampleCriteria criteria = new SampleCriteria();
		criteria = criteria.resource(id).timestamp(SampleCriteria.Oper.GT, System.currentTimeMillis() - (300 * 60 * 1000));
		List<? extends Sample> samples = os.telemetry().meters().samples("cpu_util", criteria);
		List<String> time_series = new ArrayList<String>();
		List<Float> cpu_load = new ArrayList<Float>();		
		for (Sample s: samples) {
			System.out.println(s.getCounterVolume() + s.getCounterUnit() + "\t" + s.getRecordedAt());
			time_series.add(s.getRecordedAt());
			cpu_load.add(s.getCounterVolume());
		}

		Map<Object, Object> map = new HashMap<Object, Object>();
		map.put("time_series", time_series);
		map.put("cpu_load", cpu_load);
		
		return map;
	}
}
